import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
  SafetyOutlined
} from '@ant-design/icons';
import {
  LoginForm,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
  setAlpha,
} from '@ant-design/pro-components';
import { Space, Tabs, message, theme, Modal, Form, Col, Row, Input, Button } from 'antd';
import type { CSSProperties } from 'react';
import { useState, useEffect, useRef } from 'react';
import { User, GetUserPermissions } from '@/api/userInfo'
import { flushSync } from 'react-dom';
import { FormattedMessage, history, SelectLang, useIntl, useModel, Helmet } from '@umijs/max';
import { GetCaptchaImg, PostCaptcha, Login, PostEmailCaptcha, CheckoutEmailCaptcha } from "@/api/login"
// import { GetToken } from '@/api/login'
import CryptoJS from 'crypto-js';

// type LoginType = 'email' | 'account';
const secret_key = 'adeyJ03245eXAciOiJIUzI1NiJ9'  // 临时密钥
export default () => {
  const { token } = theme.useToken();
  const [loginType, setLoginType] = useState('account');  // 登录的类型
  const { initialState, setInitialState } = useModel('@@initialState');
  const [captchaSrc, setCaptchaSrc] = useState('/assets/img/captcha.png'); // 验证码图片的URL 
  const [isModalOpen, setIsModalOpen] = useState(false);  // 弹出层
  const formRef = useRef();
  const [remenber, setRemanber] = useState('0') // 标记 1 为记住密码  0 不记住

  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const iconStyles: CSSProperties = {
    marginInlineStart: '16px',
    color: setAlpha(token.colorTextBase, 0.2),
    fontSize: '24px',
    verticalAlign: 'middle',
    cursor: 'pointer',
  };
  // 保存账号密码
  const handleRemenber = (name, pd) => {
    // 
    if (remenber === '1') {
      const jiami = CryptoJS.AES.encrypt(pd, secret_key).toString();
      window.sessionStorage.setItem('remender', remenber);
      window.sessionStorage.setItem('username', name);
      window.sessionStorage.setItem('userpd', jiami);
    } else {
      window.sessionStorage.removeItem('remender')
      window.sessionStorage.removeItem('username')
      window.sessionStorage.removeItem('userpd')
    }
  }

  // 自动登录按钮监听
  const handleCheckboxChange = (checked) => {
    // console.log(checked.target.checked ? "记住密码" : "不记住");
    // 
    if (checked.target.checked) {
      setRemanber('1')
    } else {
      window.sessionStorage.removeItem('remender')
      window.sessionStorage.removeItem('username')
      window.sessionStorage.removeItem('userpd')
      setRemanber('0')
    }

  };
  //登录提交
  const handleSubmit = async (values) => {
    console.log(values)
    // 如果用户点击的是邮箱登录 
    if (loginType === 'email') {
      try {
        const { email, email_captcha } = values
        const data = await CheckoutEmailCaptcha({ 'email_addr': email, 'email_captcha': email_captcha })
        console.log(data)
        if (data.status === 200) {
          const { access } = data
          window.localStorage.setItem('token', access);
          message.success(data.message)
        } else{
          message.error(data.message)
        }
        
      } catch (err) {
        console.log(err)
        return
      }
    } else {
      // 保存账号密码
      handleRemenber(values.username, values.password)
      try {
        // console.log('captchadata')
        const captchadata = await PostCaptcha({ 'captcha': values.captcha })
        // consoelr.log
        // console.log(captchadata)
        if (captchadata.status !== 200) {
          message.error('图形验证码错误！')
          return
        }
        const msg02 = await Login({ 'username': values.username, 'password': values.password })
        // console.log("msg02---",msg02.access)
        const { access } = msg02
        window.localStorage.setItem('token', access);
      } catch (err) {
        message.error("用户名或密码错误~")
      }
    }
    try {
      const info = await User()
      const data = await GetUserPermissions();
      if (data.data.length === 0) {
        setIsModalOpen(true);
        // 权限为0 说明没有任何权限 没有资格登录
        window.localStorage.removeItem('token')
        message.info("抱歉，请联系管理员分配权限")
        return
      }
      const remainder = info.results[0].id % 5
      flushSync(() => {
        setInitialState({
          ...initialState,
          currentUser: {
            "userinfo": info.results[0],
            "name": info.results[0].username,
            "permissionslist": data.data,
            "avatar": `/assets/img/avatar/Avatar0${remainder}.jpg`,
          }
        }
        )
      })
      // console.log(initialState)
      message.success("登录成功~")
      history.replace('/')
    } catch (error) {
      // console.log(error)
      message.error("用户名或密码错误~")
    }
  };
  // 获取验证码图片  
  const getCaptcha = async () => {
    try {
      const response = await GetCaptchaImg()
      const url = URL.createObjectURL(response)
      // console.log('url', url)
      setCaptchaSrc(url)
    } catch (err) {
      // console.log(err)
      message.info('验证码获取失败')
    }
  }
  // 初次加载 初始化验证码图片  
  useEffect(() => {
    getCaptcha();
    // console.log(window.sessionStorage.getItem('remender'))
    const logo = window.sessionStorage.getItem('remender') || '0'
    const U_name = window.sessionStorage.getItem('username') || ''
    const U_pd = window.sessionStorage.getItem('userpd') || ''
    if (logo === '1') {
      const jiemi = CryptoJS.AES.decrypt(U_pd, secret_key).toString(CryptoJS.enc.Utf8);
      // console.log(jiemi)
      setRemanber('1')
      formRef?.current?.setFieldsValue({
        username: U_name,
        password: jiemi,
        autoLogin: true,
      });
    } else {
      formRef?.current?.setFieldsValue({
        username: '',
        password: '',
        autoLogin: false,
      });
    }
  }, []);
  return (
    <ProConfigProvider hashed={false}>

      <Modal title="温馨提示：" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <br></br><p style={{ color: 'red' }}> 当前账号并未分配任何权限，请联系管理员授权后才能进行登录操作~ </p><br></br>
      </Modal>

      <div style={{ backgroundColor: token.colorBgContainer, backgroundImage: 'url(/assets/svg/bg.svg)', }} >
        <LoginForm
          title="佳立数据服务中心"
          subTitle="广州佳立供应链服务有限公司数据服务开发平台"
          formRef={formRef}
          actions={
            <Space>
              其他登录方式
              <div onClick={() => { message.error("此功能暂未开通~") }}>
                <AlipayCircleOutlined style={iconStyles} />
              </div>
              <div onClick={() => { message.error("此功能暂未开通~") }}>
                <TaobaoCircleOutlined style={iconStyles} />
              </div>
              <div onClick={() => { message.error("此功能暂未开通~") }}>
                <WeiboCircleOutlined style={iconStyles} />
              </div>
            </Space>
          }
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
        >
          <Tabs
            centered
            activeKey={loginType}
            onChange={(activeKey) => setLoginType(activeKey)}
          >
            <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
            {/* disabled禁用 */}
            <Tabs.TabPane key={'email'} tab={'邮箱验证登录'} />
          </Tabs>
          {loginType === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={'prefixIcon'} />,
                }}
                placeholder={'username: 用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={'prefixIcon'} />,
                  strengthText:
                    '密码不应该为纯数字，且长度不小于8',
                  statusRender: (value) => {
                    const getStatus = () => {
                      if (value && value.length > 12) {
                        return 'ok';
                      }
                      if (value && value.length > 6) {
                        return 'pass';
                      }
                      return 'poor';
                    };
                    const status = getStatus();
                    if (status === 'pass') {
                      return (
                        <div style={{ color: token.colorWarning }}>
                          强度：中
                        </div>
                      );
                    }
                    if (status === 'ok') {
                      return (
                        <div style={{ color: token.colorSuccess }}>
                          强度：强
                        </div>
                      );
                    }
                    return (
                      <div style={{ color: token.colorError }}>强度：弱</div>
                    );
                  },
                }}
                placeholder={'password: 密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <Form.Item extra={<span style={{ 'color': 'rgb(143 177 232)', marginLeft: '210px' }}>点击验证码可刷新</span>}>
                <Row gutter={8}>
                  <Col span={13}>
                    <Form.Item
                      name="captcha"
                      noStyle
                      rules={[{ required: true, message: '请填写验证码信息!' },
                        // {pattern: /^[0-9a-zA-Z]{4}$/, message: '验证码必须是四个字符长度，且只能包含数字和字母!'},  
                      ]}
                    >
                      <Input size="large" prefix={<SafetyOutlined />} placeholder="图形验证码" maxLength={4} />
                    </Form.Item>
                  </Col>
                  <Col span={9} offset={2}>
                    {/*  */}
                    <a><img src={captchaSrc} style={{ height: '100%' }} onClick={getCaptcha} /></a>
                    {/* </Button> */}
                  </Col>
                </Row>
              </Form.Item>
              <div style={{ margin: ' 6px 0px' }}>
                <ProFormCheckbox noStyle name="autoLogin" onChange={handleCheckboxChange} >
                  记住账户<span style={{ 'color': 'rgb(143 177 232)' }}>（浏览器关闭后失效）</span>
                </ProFormCheckbox>
              </div>
            </>
          )}
          {loginType === 'email' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={'prefixIcon'} />,
                }}
                name="email"
                placeholder={'邮箱验证登录'}
                rules={[
                  {
                    type: 'email',
                    message: '邮箱格式不正确！',
                  },
                  {
                    required: true,
                    message: '请填写您注册时绑定的邮箱',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={'prefixIcon'} />,
                }}

                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码'}
                countDown={10}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'s可获取验证码'}`;
                  }
                  return '获取验证码';
                }}
                phoneName="email"
                name="email_captcha"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                ]}
                onGetCaptcha={async (email) => {
                  try {
                    const data = await PostEmailCaptcha({ 'email': email })
                    console.log(data)
                    if (data.status === 200) {
                      message.success(data.message)
                      return
                    }
                    message.error(data.message)
                    //  ('获取验证码成功！验证码为：1234');
                  } catch (err) {
                    message.error('验证码获取失败')
                    console.log(err)
                  }

                }}
              />
            </>
          )}

          <div
            style={{
              marginBlockEnd: 24,
            }}
          >

            <a
              onClick={() => { history.push('/user/register'); }}
            >
              新用户注册
            </a>
            <a
              style={{
                float: 'right'
              }}
              onClick={() => { message.error("此功能暂未开通，密码忘记请联系管理员~") }}
            >
              忘记密码 ?
            </a>
          </div>
        </LoginForm>
      </div>
    </ProConfigProvider>
  );
};